<template>
  <el-dialog
    class="gl_dialog_TitleLine"
    width="1080px"
    title="上传图片"
    :append-to-body="true"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <photo-cropper ref="photoCropper" :action="action" :option="option" height="550px" @photoCropperSave="photoCropperSave" />
  </el-dialog>
</template>
<script>
import photoCropper from '@/components/PhotoCropper';
export default {
  name: 'PhotoCropperDialog',
  components: {
    photoCropper
  },
  props: {
    autoCropWidth: {
      type: String,
      required: false,
      default: '200px'
    },
    autoCropHeight: {
      type: String,
      required: false,
      default: '200px'
    },
    enlarge: {
      type: Number,
      required: false,
      default: 1
    },
    fixedNumber: {
      type: Array,
      required: false,
      default: function() {
        return [1, 1];
      }
    }
  },
  data() {
    return {
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`,
      dialogVisible: false,
      option: {
        img: ''
      }
    };
  },
  methods: {
    init() {},
    open(imgUrl) {
      if (imgUrl) {
        this.$set(this.option, 'img', this.getStaticPhotoUrl(imgUrl));
      }
      this.$set(this.option, 'autoCropWidth', this.autoCropWidth);
      this.$set(this.option, 'autoCropHeight', this.autoCropHeight);
      this.$set(this.option, 'enlarge', this.enlarge);
      this.$set(this.option, 'fixedNumber', this.fixedNumber);
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.photoCropper.init();
      });
    },
    // 点击保存
    photoCropperSave(uploadImg) {
      this.$refs.photoCropper.upload().then(res => {
        this.$emit('photoCropperSave', res);
        this.dialogVisible = false;
      });
    },
    // 获取静态文件
    getStaticPhotoUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 文件格式转图片路径
    fileToImg(file) {
      return new Promise(resolve => {
        const fileReader = new FileReader();
        fileReader.readAsDataURL(file);
        fileReader.onloadend = () => {
          resolve(fileReader.result);
        };
      });
    }
  }
};
</script>

